package com.tanx.service.operator;

import com.tanx.context.BeanProvider;
import com.tanx.dao.UserRepository;
import com.tanx.dto.user.UserFormDto;
import com.tanx.entity.User;
import org.apache.commons.lang.StringUtils;

/**
 * Created by 唐旭 on 2015/10/12.
 */
public class UserFormDtoPersister {
    private transient UserRepository repository = BeanProvider.getBean(UserRepository.class);

    private UserFormDto formDto;

    public UserFormDtoPersister(UserFormDto formDto) {
        this.formDto = formDto;
    }

    public void persist() {
        if (StringUtils.isEmpty(formDto.getUuid())) {
            createNewUser();
        } else {
            updateUser();
        }
    }

    private void updateUser() {
        User user = repository.findOne(formDto.getUuid());
        user.setName(formDto.getName());
        repository.save(user);
    }

    private void createNewUser() {
        User user = new User()
                .setName(formDto.getName());
        repository.save(user);
    }

}
